<?php
	App::import("Vendor","PaidListings.PaidListingNotification");
	App::import("Model","PaidListings.Plan");
	App::import("Vendor","PaidListings.Metrics");
	class Order extends AppModel
	{
		var $name = "Order";
		//order hasn't been intiated by user
		const STATUS_PENDING = 0;
		//order has been intiated by user by payment is pending
		const STATUS_INCOMPLETE = 1;
		//order has initiated and payment is in progress
		const STATUS_PROCESSING = 2;
		const STATUS_FRAUD = 3;
		const STATUS_FAILED = 4;
		//order payment was successfull.
		const STATUS_COMPLETED = 5;
		var $additionalFields = array(
			'total_amount',
			'payment_handler'
		);
		var $cacheFields = array(
			'payment_handler'=>"onUpdate"
		);
		var $actsAs = array(
					'Cms.Metric' => array(
							array("metric"=>'PaidListingRevenueAmount')	,
							array('metric' => 'NumRecords','title'=>"Orders",'scope'=>array("Order.status"=>self::STATUS_COMPLETED,'Not'=>array("Order.payment_type"=>Plan::PAYMENT_TRIAL))),
					),
		);
		function initialize()
		{
			$this->fieldProperties['status'] = array('type'=>'select','group'=>"search",'label'=>__("Payment Status"),'options'=>array(Order::STATUS_PENDING => __("Pending"),Order::STATUS_INCOMPLETE=>__("Incomplete"),
				Order::STATUS_PROCESSING => __("Processing"),Order::STATUS_FRAUD => __("Fraud") ,Order::STATUS_COMPLETED => __("Completed")));
			parent::initialize();
		}
		var $hasMany = array("Transaction"=>array(
			'className' => 'PaidListings.Transaction',
			'dependent' => true,
		));
		var $belongsTo = array(
			'ListingPlan' => array(
				'className' => 'PaidListings.ListingPlan',
			),
		);
		function afterInitialize()
		{
			if(!AppUtility::allowPaidListing())
			{
				unset($this->actsAs['Cms.Metric']);
			}
			$this->ListingPlan = cri("PaidListings.ListingPlan");
            $this->setFieldProperties('payment_type', array("options"=>cri("PaidListings.Plan")->getFieldProperty('payment_type','options')));
			$this->setFieldProperties('id', array("type"=>'number','label'=>__("Order Id"),'group'=>"search"));
            $this->setFieldProperties('plan_id', array("type"=>"select",'group'=>"search",'options'=>array(),'label'=>__("Plan")));
            $handlers = cri('PaidListings.PaymentHandler')->getPaymentHandlers();
            $handlers = array_keys($handlers);
            $handlers = array_combine($handlers,$handlers);
            $this->setFieldProperties('payment_handler', array("type"=>"select",'group'=>"search",'label'=>"Payment method",'options'=>$handlers));
            $this->setFieldProperties('payment_type', array("type"=>"select",'group'=>"search"));
            $this->setFieldProperties('listing_plan_status', array("type"=>"select",'group'=>"search",'label'=>__("Plan Status"),'options'=>$this->ListingPlan->getFieldProperty('status','options')));
            parent::afterInitialize();
		}
		
		function total_amount($order)
		{
			$totalAmount = false;
			if(isset($order['Order']['price']))
			{
				$tax = 0;
				if($order['Order']['tax'])
				{
					$tax = $order['Order']['tax'];
				}
				$totalAmount = $order['Order']['price'] + (($order['Order']['price']*$tax)/100);
				$totalAmount = round($totalAmount,2);
			}
			return $totalAmount;
		}
		function initOrder($listingPlanId)
		{
			$listingPlan = $this->ListingPlan->getListingPlanInfo($listingPlanId);
			$plan = $listingPlan['ListingPlan']['plan_info'];
			$tax = cr('PaidListingConfig.tax');
			if(!$tax)
			{
				$tax = 0;
			}
			$data = array('payment_type'=>$plan['Plan']['payment_type'],"status"=>self::STATUS_PENDING,'price'=>$plan['Plan']['price'],'currency'=>cr('PaidListingConfig.currency'),
			'currency_symbol'=>cr('PaidListingConfig.currency_symbol'),'tax'=>$tax,'listing_plan_id'=>$listingPlanId,'plan_id'=>$plan['Plan']['id'],
			'duration_number' => $plan['Plan']['duration_number'] ,'duration_period'=>$plan['Plan']['duration_period']);
			$this->create();
			$this->save(array($this->alias => $data));
			$id = $this->id;
			$this->recursive = -1;
			if($plan['Plan']['payment_type'] != Plan::PAYMENT_TRIAL)
			{
				$order = $this->findById($id);
				//PaidListingNotification::getInstance()->orderCreated($order);
			}
			return $id;
		}
		
		function setAsCompleted($orderId)
		{
			$this->recursive = -1;
			$order = $this->findById($orderId);
			$this->id = $orderId;
			$listingPlan = $this->ListingPlan->getListingPlanInfo($order[$this->alias]['listing_plan_id']);
			$plan = $listingPlan['ListingPlan']['plan_info'];
			if($plan['Plan']['payment_type'] != Plan::PAYMENT_TRIAL && $plan['Plan']['duration_period'])
			{
				$timeStr = $plan['Plan']['duration_number'].' '. $plan['Plan']['duration_period'];
				$endDate = strtotime('+'.$timeStr);
				$endDate = date("Y-m-d",$endDate);
			}else
			{
				$endDate = null;
			}
			$this->saveField("status",self::STATUS_COMPLETED);
			$this->saveField("start_date",date("Y-m-d"));
			$this->saveField("end_date",$endDate);
			$ListingModel = cri("Listing");
			$ownerId = $ListingModel->field("owner_id",array("id"=>$listingPlan['ListingPlan']['listing_id']));
			if(!$ownerId)
			{
				$ownerCandidateId = $ListingModel->field("owner_candidate_id",array("id"=>$listingPlan['ListingPlan']['listing_id']));
				if($ownerCandidateId)
				{
					$ListingModel->id = $listingPlan['ListingPlan']['listing_id'];
					$ListingModel->saveField("owner_id",$ownerCandidateId);
					$ListingModel->saveField("owner_candidate_id",null);
					//cri("ListingClaim")->updateAll(array("ListingClaim.status"=>ListingClaim::STATUS_ASSIGNED),array('ListingClaim.user_id'=>$ownerCandidateId,'ListingClaim.listing_id'=>$listingPlan['ListingPlan']['listing_id']));
				}
			}
			$this->ListingPlan->activatePlan($order[$this->alias]['listing_plan_id']);
		}
		
		function setAsIncomplete($orderId)
		{
			$this->recursive = -1;
			$order = $this->findById($orderId);
			$this->id = $orderId;
			$this->saveField("status",self::STATUS_INCOMPLETE);
		}
		
		function setAsProcessing($orderId)
		{
			$this->recursive = -1;
			$order = $this->findById($orderId);
			$this->id = $orderId;
			$this->saveField("status",self::STATUS_PROCESSING);
		}
		
		function setAsFraud($orderId)
		{
			$this->recursive = -1;
			$order = $this->findById($orderId);
			$this->id = $orderId;
			$this->saveField("status",self::STATUS_FRAUD);
		}
		function setAsFailed($orderId)
		{
			$this->recursive = -1;
			$order = $this->findById($orderId);
			$this->id = $orderId;
			$this->saveField("status",self::STATUS_FRAUD);
		}
		function getLatestOrder($listingPlanId)
		{
			return $this->find("first",array("conditions"=>array('listing_plan_id'=>$listingPlanId),'recursive'=>-1,'order'=>"created desc"));
		}
		/**
		 * 
		 */
		function reImplement($orderId)
		{
			$this->recursive =0;
			$order = $this->findById($orderId);
			$deActivate = false;
			$endDate = $order['Order']['end_date'];
			if($endDate)
			{
				$endDate = strtotime($endDate);
				if($endDate < time())
				{
					$deActivate = false;
				}
			}
			if($deActivate && $order['ListingPlan']['status'] != ListingPlan::STATUS_INACTIVE)
			{
				$this->ListingPlan->id = "";
				$this->ListingPlan->saveField('status',ListingPlan::STATUS_INACTIVE);
			}
			$EffectivePlan = $this->ListingPlan->getEffectivePlan($order['ListingPlan']['listing_id'],true);			
			$EffectivePlan->implementDecrementally();		
		}
		
		function payment_handler($order)
		{
			$paymentHandler = $this->Transaction->field("payment_handler",array("order_id"=>$order['Order']['id'],'Transaction.status'=>Transaction::SUCCESSFUL),'Transaction.id DESC');
			if(!$paymentHandler)
			{
				$paymentHandler = null;
			}
			return $paymentHandler;
		}
        
        function getSearchFields()
        {
            return array('id','status','payment_status','');
        }
	}
?>